package com.atguigu.smsservice.controller;

import com.atguigu.commonutils.R;
import com.atguigu.smsservice.service.SmsService;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author alan
 */
@RestController
@RequestMapping("/msmService/msm")
@CrossOrigin
public class SmsController {

    @Resource
    private SmsService smsService;

    @ApiOperation("/发送注册验证码")
    @PostMapping("/code/register/{phone}")
    public R sendRegisterCode(@PathVariable("phone") String phone) {

        String errorMsg = checkPhone(phone);
        if (StringUtils.isNotEmpty(errorMsg)) {
            return R.error(errorMsg);
        }
        if (smsService.sendRegisterCode(phone)) {
            return R.ok("发送成功,验证码有效期为五分钟");
        }
        return R.error("发送失败,请重试");

    }

    @ApiOperation("/发送登录验证")
    @PostMapping("/code/login/{phone}")
    public R sendLoginCode(@PathVariable("phone") String phone) {

        String errorMsg = checkPhone(phone);
        if (StringUtils.isNotEmpty(errorMsg)) {
            return R.error(errorMsg);
        }
        if (smsService.sendLoginCode(phone)) {
            return R.ok("发送成功,验证码有效期为五分钟");
        }
        return R.error("发送失败,请重试");

    }

    /**
     * 检验手机格式是否正确
     */
    private String checkPhone(String phone) {
        if (StringUtils.isEmpty(phone) || phone.length() != 11) {
            return "请输入正确的手机号码";
        }
        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(phone);
        if (!m.matches()) {
            return "请输入正确的手机号码";
        }
        return null;
    }


}
